﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GTAuto.DAL.DAL;
using GTAuto.DAL.Entities;
using GTAuto.Site.BackEnd.ApCode.Filters;


namespace GTAuto.Site.BackEnd.Controllers
{
     [AutoSection]
    public class TiresModificationsController : Controller
    {
        //
        // GET: /ModelModifications/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ByModel(int id)
        {
            var mode = DALModels.Singleton.Get(id);

            ViewBag.ModelName = mode.NameDate;
            ViewBag.BrandName = mode.Brand.Name;

            List<GTModelModification> gtModelModifications = DALModelModification.Singleton.GetAll(id);
            Session["CurModel"] = id;
            Session["CurBrand"] = mode.BrandId;

            return View(gtModelModifications);
        }


        public ActionResult ModificationEdit(int? id)
        {

            if (Session["CurModel"] == null)
                RedirectToAction("Index");


            GTModelModification brand = null;
            brand = id == null ? new GTModelModification() : DALModelModification.Singleton.Get((int)id);

            int count;
            var mod = DALModels.Singleton.Get((int)Session["CurModel"]);
            ViewBag.ModelName = mod.NameDate;

            List<GTModelModificationProperty> gtModelModificationProperties = DALModelModificationProperty.Singleton.GetByModel(mod.Id);

            var activeCategories = new List<GTPropertyCategory>();

            foreach (var gtModelModificationProperty in gtModelModificationProperties)
            {
                GTPropertyCategory category = DALPropertyCategory.Singleton.Get(gtModelModificationProperty.ModificationProperty.Category);
                

                bool needToAdd = true;
                foreach (var it in activeCategories)
                {
                    if (it.Id == category.Id) needToAdd = false;
                }
                
                if (needToAdd)
                    activeCategories.Add(category);
            }

            ViewBag.ActivCategories = activeCategories;
            ViewBag.ModelModificationProperties = gtModelModificationProperties;

            return View(brand);
        }

        [HttpPost]
        public ActionResult ModificationEdit(GTModelModification gtBrand, FormCollection formCollection, HttpPostedFileBase LogoPath, HttpPostedFileBase SmallLogoPath)
        {

            if (Session["CurModel"] == null)
                RedirectToAction("Index");


            gtBrand.ModelId = (int)Session["CurModel"];

            int count;
            var mod = DALModels.Singleton.Get((int)Session["CurModel"]);
            ViewBag.ModelName = mod.NameDate;

            List<GTModelModificationProperty> gtModelModificationProperties = DALModelModificationProperty.Singleton.GetByModel(mod.Id);
            var activeCategories = new List<GTPropertyCategory>();
            foreach (var gtModelModificationProperty in gtModelModificationProperties)
            {
                GTPropertyCategory category = DALPropertyCategory.Singleton.Get(gtModelModificationProperty.ModificationProperty.Category);
                bool needToAdd = true;
                foreach (var it in activeCategories)
                {
                    if (it.Id == category.Id) needToAdd = false;
                }
                if (needToAdd)
                    activeCategories.Add(category);
            }
            ViewBag.ActivCategories = activeCategories;
            ViewBag.ModelModificationProperties = gtModelModificationProperties;
            
            List<string> Error = new List<string>();
            
            if (string.IsNullOrEmpty(gtBrand.Name))
                Error.Add("Название не может быть пустым");


            if (LogoPath != null)
            {

                string filename = Guid.NewGuid().ToString() + "." + LogoPath.FileName.Split('.')[1];

                string filePath = Path.Combine(HttpContext.Server.MapPath(Url.Content(@"/Uploads/BrendLogos/"))
               , Path.GetFileName(filename));

                LogoPath.SaveAs(filePath);
                gtBrand.LogoPath = filename;
            }

            if (SmallLogoPath != null)
            {
                string filename = Guid.NewGuid().ToString() + "." + SmallLogoPath.FileName.Split('.')[1];

                string filePath = Path.Combine(HttpContext.Server.MapPath(Url.Content(@"/Uploads/BrendLogos/"))
               , Path.GetFileName(filename));
                SmallLogoPath.SaveAs(filePath);
                gtBrand.SmallLogoPath = filename;
            }





            if (Error.Count == 0)
            {
                if (gtBrand.Id > 0)
                {
                    var oldBrand = DALModelModification.Singleton.Get(gtBrand.Id);

                    if (string.IsNullOrEmpty(gtBrand.LogoPath))
                        gtBrand.LogoPath = oldBrand.LogoPath;

                    if (string.IsNullOrEmpty(gtBrand.SmallLogoPath))
                        gtBrand.SmallLogoPath = oldBrand.SmallLogoPath;


                    DALModelModification.Singleton.Update(gtBrand);
                }
                else
                {
                    gtBrand = DALModelModification.Singleton.Add(gtBrand);
                }

                foreach (var prop in gtModelModificationProperties)
                {
                  var mp =  DALModificationPropertyValue.Singleton.Get(gtBrand.Id, prop.PropertyId);
                  if(mp==null)
                  {
                      var temp = new GTModificationPropertyValue();
                      temp.ModificationId = gtBrand.Id;
                      temp.PropertyId = prop.PropertyId;
                      temp.Value = formCollection["prop_" + prop.PropertyId];
                      DALModificationPropertyValue.Singleton.Add(temp);
                  }
                  else
                  {
                      mp.Value = formCollection["prop_" + prop.PropertyId];
                      DALModificationPropertyValue.Singleton.Update(mp);
                  }
                }

                return RedirectToAction("ByModel", new { @id = gtBrand.ModelId });
            }
            else
            {
                gtBrand.LogoPath = "";
                gtBrand.SmallLogoPath = "";
            }


            ViewBag.Errs = Error;

            return View(gtBrand);
        }


        public ActionResult Delete(int id)
        {
            var modId = DALModelModification.Singleton.Get(id).ModelId;

            DALModelModification.Singleton.Delete(id);
            return RedirectToAction("ByModel", new { @id = modId });
        }


    }
}
